package cn.tx.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author Mxb
 * @version 1.0
 * @date 2020/10/12 20:53
 */
@Component
public class WatchMessageImpl implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void initRabbitTemplate() {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnCallback(this);
    }

    /**
     * 消息到达交换机的回调
     * @param correlationData
     * @param ack             是否到达交换机
     * @param cause
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack) {
            System.out.println("===消息正常到达交换机===");
        } else {
            System.out.println("===消息没有到达交换机原因：" + cause);
        }
    }

    /**
     * 消息由交换机到达队列失败之后的回调
     * @param message    消息体
     * @param replyCode  回调的状态码
     * @param replyText  文本
     * @param exchange   交换机的名称
     * @param routingKey 路由名
     */
    @Override
    public void returnedMessage(Message message, int replyCode, String
            replyText, String exchange, String routingKey) {
        System.out.println("===消息未正常到达队列===");
        System.out.println("消息内容: " + message);
        System.out.println("回退的响应码replyCode: " + replyCode);
        System.out.println("响应文本replyText: " + replyText);
        System.out.println("交互机exchange: " + exchange);
        System.out.println("消息路由keyroutingKey: " + routingKey);
        //处理重新发送的问题
    }
}
